<template>
  <div class="priority-management-container">
    <div class="page-header">
      <h1>优先级管理</h1>
      <p>管理系统中各模块的优先级配置</p>
    </div>

    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>优先级列表</span>
          <div>
            <el-button type="primary" @click="handleCreate">新增优先级</el-button>
            <el-dropdown @command="handleRefreshCommand" :disabled="refreshing">
              <el-button :loading="refreshing">
                刷新缓存
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="current">
                    刷新当前模块（{{ getModuleName(activeModule) }}）
                  </el-dropdown-item>
                  <el-dropdown-item command="all" divided>
                    刷新所有模块
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeModule" @tab-click="handleModuleChange">
        <el-tab-pane v-for="module in modules" :key="module.value" :label="module.label" :name="module.value">
          <div class="tab-toolbar">
            <el-button type="primary" plain @click="handleInitialize(module.value)">初始化默认优先级</el-button>
            <el-button 
              type="info" 
              plain 
              @click="handleRefreshModule(module.value)"
              :loading="refreshing && refreshingModule === module.value"
            >
              刷新当前模块缓存
            </el-button>
          </div>
          <el-table :data="priorityList" v-loading="loading" border stripe>
            <el-table-column prop="name" label="优先级名称" width="150" />
            <el-table-column prop="module_type" label="模块" width="120">
              <template #default="{ row }">
                {{ getModuleName(row.module_type) }}
              </template>
            </el-table-column>
            <el-table-column prop="code" label="优先级代码" width="150" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="color" label="颜色" width="120">
              <template #default="{ row }">
                <div class="color-block-wrapper">
                  <div class="color-block" :style="{ backgroundColor: row.color }"></div>
                  <span>{{ row.color }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sort_order" label="排序" width="80" />
            <el-table-column prop="is_enabled" label="启用状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.is_enabled ? 'success' : 'info'">
                  {{ row.is_enabled ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                <el-button type="primary" link @click="handleToggleEnabled(row)">
                  {{ row.is_enabled ? '禁用' : '启用' }}
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 新增/编辑优先级弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="handleCloseDialog">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="模块" prop="module_type">
          <el-select v-model="form.module_type" placeholder="请选择模块" :disabled="isEdit">
            <el-option
              v-for="module in modules"
              :key="module.value"
              :label="module.label"
              :value="module.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优先级名称"></el-input>
        </el-form-item>
        <el-form-item label="优先级代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入优先级代码"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="form.color" />
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="form.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="是否启用" prop="is_enabled">
          <el-switch v-model="form.is_enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { priorityApi } from '@/api/priority'

// 模块列表
const modules = [
  { label: '任务', value: 'task' },
  { label: '项目', value: 'project' },
  { label: '缺陷', value: 'defect' },
  { label: '需求', value: 'requirement' },
  { label: '测试', value: 'test_case' }
]

// 响应式数据
const activeModule = ref('task')
const priorityList = ref<any[]>([])
const loading = ref(false)
const refreshing = ref(false)
const refreshingModule = ref<string | null>(null)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const form = ref<any>({})
const isEdit = ref(false)

const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入优先级名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入优先级代码', trigger: 'blur' }],
  module_type: [{ required: true, message: '请选择模块', trigger: 'change' }]
})

// 获取优先级列表
const fetchPriorities = async (module: string) => {
  loading.value = true
  try {
    const res = await priorityApi.getAll(module)
    priorityList.value = res.data?.data || []
  } catch (error) {
    console.error('获取优先级列表失败:', error)
    ElMessage.error('获取优先级列表失败')
  } finally {
    loading.value = false
  }
}

// 处理模块切换
const handleModuleChange = (tab: any) => {
  fetchPriorities(tab.props.name)
}

// 处理刷新缓存命令
const handleRefreshCommand = async (command: string) => {
  if (command === 'current') {
    await handleRefreshModule(activeModule.value)
  } else if (command === 'all') {
    await handleRefreshAll()
  }
}

// 刷新单个模块缓存
const handleRefreshModule = async (module: string) => {
  try {
    await ElMessageBox.confirm(
      `确定要刷新"${getModuleName(module)}"模块的优先级缓存吗？`,
      '确认刷新',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    refreshing.value = true
    refreshingModule.value = module
    
    try {
      const res = await priorityApi.refreshCache(module)
      ElMessage.success(res.data?.message || `刷新"${getModuleName(module)}"模块缓存成功`)
      
      // 如果刷新的是当前模块，重新加载数据
      if (module === activeModule.value) {
        await fetchPriorities(module)
      }
    } finally {
      refreshing.value = false
      refreshingModule.value = null
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('刷新优先级缓存失败:', error)
      ElMessage.error('刷新优先级缓存失败')
      refreshing.value = false
      refreshingModule.value = null
    }
  }
}

// 刷新所有模块缓存
const handleRefreshAll = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要刷新所有模块的优先级缓存吗？此操作将清除所有模块的缓存数据。',
      '确认刷新',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    refreshing.value = true
    
    try {
      const res = await priorityApi.refreshCache()
      ElMessage.success(res.data?.message || '所有模块的优先级缓存已刷新')
      
      // 重新加载当前模块的数据
      await fetchPriorities(activeModule.value)
    } finally {
      refreshing.value = false
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('刷新优先级缓存失败:', error)
      ElMessage.error('刷新优先级缓存失败')
      refreshing.value = false
    }
  }
}

// 处理初始化
const handleInitialize = async (module: string) => {
  try {
    await ElMessageBox.confirm(`确定要为"${getModuleName(module)}"模块初始化默认优先级吗？这将覆盖现有配置。`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await priorityApi.initialize(module)
    ElMessage.success(res.data.message)
    
    // 初始化后自动刷新对应模块的缓存
    try {
      await priorityApi.refreshCache(module)
    } catch (refreshError) {
      console.warn('刷新缓存失败，但不影响操作:', refreshError)
    }
    
    fetchPriorities(activeModule.value)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('初始化失败:', error)
      ElMessage.error('初始化失败')
    }
  }
}

// 处理新增
const handleCreate = () => {
  isEdit.value = false
  dialogTitle.value = '新增优先级'
  form.value = {
    module_type: activeModule.value,
    color: '#1890ff',
    sort_order: 0,
    is_enabled: true
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: any) => {
  isEdit.value = true
  dialogTitle.value = '编辑优先级'
  form.value = { ...row }
  dialogVisible.value = true
}

// 处理启用/禁用
const handleToggleEnabled = async (row: any) => {
  const actionText = row.is_enabled ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(`确定要${actionText}"${row.name}"吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await priorityApi.update(row._id, { is_enabled: !row.is_enabled })
    ElMessage.success(`${actionText}成功`)
    row.is_enabled = !row.is_enabled
    
    // 刷新对应模块的缓存，确保状态同步
    try {
      await priorityApi.refreshCache(row.module_type)
    } catch (refreshError) {
      console.warn('刷新缓存失败，但不影响操作:', refreshError)
    }
    
    fetchPriorities(activeModule.value)
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${actionText}失败:`, error)
      ElMessage.error(`${actionText}失败`)
    }
  }
}

// 处理删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    const moduleType = row.module_type
    await priorityApi.delete(row._id)
    ElMessage.success('删除成功')
    
    // 刷新对应模块的缓存，确保数据同步
    try {
      await priorityApi.refreshCache(moduleType)
    } catch (refreshError) {
      console.warn('刷新缓存失败，但不影响操作:', refreshError)
    }
    
    fetchPriorities(activeModule.value)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理弹窗关闭
const handleCloseDialog = () => {
  formRef.value?.resetFields()
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await priorityApi.update(form.value._id, form.value)
          ElMessage.success('更新成功')
        } else {
          await priorityApi.create(form.value)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        
        // 刷新当前模块的缓存，确保数据同步
        try {
          await priorityApi.refreshCache(form.value.module_type)
        } catch (refreshError) {
          console.warn('刷新缓存失败，但不影响操作:', refreshError)
        }
        
        fetchPriorities(activeModule.value)
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 获取模块中文名
const getModuleName = (module: string) => {
  return modules.find(m => m.value === module)?.label || module
}

// 初始化
onMounted(() => {
  fetchPriorities(activeModule.value)
})
</script>

<style scoped>
.priority-management-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #606266;
  margin: 0;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tab-toolbar {
  margin-bottom: 16px;
}

.color-block-wrapper {
  display: flex;
  align-items: center;
}

.color-block {
  width: 16px;
  height: 16px;
  border-radius: 2px;
  margin-right: 8px;
  border: 1px solid #dcdfe6;
}
</style>
